package com.zeldu.teacher.homework.service;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zeldu.common.exception.CustomException;
import com.zeldu.common.model.response.CommonCode;
import com.zeldu.common.model.response.QueryResponseResult;
import com.zeldu.common.model.response.QueryResult;
import com.zeldu.common.model.response.ResponseResult;
import com.zeldu.teacher.homework.Dto.*;

import com.zeldu.teacher.homework.entity.*;
import com.zeldu.teacher.homework.mapper.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class TeacherService {
    @Autowired
    QuestionMapper questionMapper;
    @Autowired
    Content_HomewrokMapper content_homewrokMapper;
    @Autowired
    HomeworkMapper homeworkMapper;
    @Autowired
    Course_StudentMapper course_studentMapper;
    @Autowired
    Student_HomeWrokMapper student_homeWrokMapper;
    @Autowired
    StudentMapper studentMapper;
    public QueryResponseResult<HomeWrokDetailDto_T> findAllQuestion(Long tid) {
        List<Question> allQuestion = questionMapper.findAllQuestion(tid);

        List<HomeWrokDetailDto_T> homeWrokDetailDto_ts=new ArrayList<>();
        for (Question question : allQuestion) {

             HomeWrokDetailDto_T parse = JSON.parseObject(question.getQuestion(),HomeWrokDetailDto_T.class);
            parse.setId(question.getId().toString());
            homeWrokDetailDto_ts.add(parse);
        }

        QueryResult<HomeWrokDetailDto_T> queryResult=new QueryResult<>();
        queryResult.setList(homeWrokDetailDto_ts);
        queryResult.setTotal(homeWrokDetailDto_ts.size());
        QueryResponseResult<HomeWrokDetailDto_T> questionQueryResponseResult=new QueryResponseResult<>(CommonCode.SUCCESS,queryResult);

        return questionQueryResponseResult;

    }


    public ResponseResult SetHomeWrokToStudent(String ids,  Integer cid, String startTime, String endTime,String name){
        if(ids==null||cid==null||startTime==null||endTime==null||name==null
                ||"".equals(ids)||"".equals(name)){
            throw new CustomException(CommonCode.FAIL);
        }
        Long tid=1286977770684948448l;

        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd'T'HH:mm");
         Date start=null;
        Date end=null;
        try {
            start = simpleDateFormat.parse(startTime);
            end = simpleDateFormat.parse(endTime);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        List<IDTO> idtos = JSON.parseArray(ids, IDTO.class); //老师所选的所有课程的id
        final List<HomeWrokDetailDto> questions = getQuestions(idtos, tid);//选出所有题目

         String jsonString = JSON.toJSONString(questions);
         Homewrok homewrok=new Homewrok();
        homewrok.setTeacherId(tid);
        homewrok.setCourseId(cid);
        homewrok.setStartTime(new Timestamp(start.getTime()));
        homewrok.setEndTime(new Timestamp(end.getTime()));
        homewrok.setHomeworkName(name);
        homeworkMapper.insert(homewrok);
        Homewrok homewrok1 =null;
        try {
            homewrok1 = homeworkMapper.selectOne(new LambdaQueryWrapper<Homewrok>().eq(Homewrok::getCourseId, cid).eq(Homewrok::getTeacherId, tid).eq(Homewrok::getHomeworkName, name));
       }catch (Exception e){
           throw new CustomException(CommonCode.ExistCourse);
       }

      //开始插入到对应的作业里面方便学生查看
//        InsertToStudent(cid,tid,homewrok1.getId(),jsonString);
        SetHomeWrokToAllStudent(homewrok1.getId(),cid,jsonString,name,new Timestamp(start.getTime()),new Timestamp(end.getTime()));
        return new ResponseResult(CommonCode.SUCCESS);
    }

    private List<Course_Student> selectByCid(Integer cid){
        return course_studentMapper.selectByCourseId(cid);
    }


    private void SetHomeWrokToAllStudent(Long hid,Integer cid,String content,String hname,Timestamp startTime,Timestamp endTime){
         List<Course_Student> course_students = selectByCid(cid);
        List<Student_HomeWrok> list =new ArrayList<>();
        for (int i = 0; i < course_students.size(); i++) {
            Student_HomeWrok h=new Student_HomeWrok();
            h.setEndTime(endTime);
            h.setStartTime(startTime);
            h.setHomeworkId(hid);
            h.setHomeworkContent(content);
            h.setHomeworkName(hname);
            h.setSutdentId(course_students.get(i).getStudentId());
            h.setScore(null);
            h.setStatus(0);
            h.setDoTime(null);
            h.setDoneTime(null);
            h.setMyAnswer(null);
            list.add(h);
        }
        student_homeWrokMapper.insertPatchToDO(list);

    }

    private Timestamp get(String time){
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:sss");
        Date parse = null;
        try {
            parse = simpleDateFormat.parse(time);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return (Timestamp) parse;
    }
    //生产对应作业
    private boolean InsertToStudent(Integer cid,Long tid,Long hid,String jsonString){
        // 插入对应的作业内容
        //
        Content_Homewrok content_homewrok=new Content_Homewrok();
        content_homewrok.setContent(jsonString);
        content_homewrok.setCourseId(cid);
        content_homewrok.setTeacherId(tid);
        content_homewrok.setHomeworkId(hid);
        content_homewrokMapper.insert(content_homewrok);
        return  true;
    }

    //选出题目
    private List<HomeWrokDetailDto> getQuestions( List<IDTO> idtos,Long tid){
        List<Long> ids=new ArrayList<>();
        for (int i = 0; i < idtos.size(); i++) {
            ids.add(idtos.get(i).getId());
        }
//         List<Question> questions = questionMapper.selectList(new LambdaQueryWrapper<Question>().in(Question::getId, ids).eq(Question::getTeacherId, tid));
         List<Question> exQuestions = questionMapper.findExQuestions(ids, tid);
        List<HomeWrokDetailDto> homeWrokDetailDtoList=new ArrayList<>();
        for (int i=0;i<exQuestions.size();i++){
             String question = exQuestions.get(i).getQuestion();
             HomeWrokDetailDto homeWrokDetailDto = JSON.parseObject(question, HomeWrokDetailDto.class);
            homeWrokDetailDtoList.add(homeWrokDetailDto);
        }
        return homeWrokDetailDtoList;
    }

    private boolean InsertToHQ( List<IDTO> idtos ,Long hid){
        return true;
    }



    public QueryResponseResult<HomeWrok_TDto> show(Integer cid) {
        Long tid=1286977770684948448l;
         List<Homewrok> homewroks = homeworkMapper.selectList(new LambdaQueryWrapper<Homewrok>().eq(Homewrok::getCourseId, cid)
                .eq(Homewrok::getTeacherId, tid));
         QueryResult<HomeWrok_TDto> queryResult=new QueryResult<>();
         List<HomeWrok_TDto> list=new ArrayList<>();
        for (int i = 0; i <homewroks.size() ; i++) {
             Homewrok homewrok = homewroks.get(i);
            HomeWrok_TDto t=new HomeWrok_TDto();
            t.setEndTime(getTime(homewrok.getEndTime()));
            t.setHomeworkId(homewrok.getId().toString());
            t.setHomeworkName(homewrok.getHomeworkName());
            t.setStartTime(getTime(homewrok.getStartTime()));
                list.add(t);
        }

         queryResult.setTotal(list.size());
         queryResult.setList(list);
         QueryResponseResult<HomeWrok_TDto> queryResponseResult=new QueryResponseResult<>(CommonCode.SUCCESS,queryResult);
         return queryResponseResult;
    }
    private String getTime(Timestamp timestamp){
        final SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        final String format = simpleDateFormat1.format(timestamp);
        return format;
    }
    public QueryResponseResult<StudentDto> showStudent(Long hid) {
         List<Student_HomeWrok> student_homeWroks = student_homeWrokMapper.selectList(new LambdaQueryWrapper<Student_HomeWrok>().
                 eq(Student_HomeWrok::getHomeworkId, hid));


         List<StudentDto> studentDtos=new ArrayList<>();
        for (int i = 0; i < student_homeWroks.size(); i++) {
             Student_HomeWrok tmp = student_homeWroks.get(i);
            StudentDto studentDto=new StudentDto();
            studentDto.setDoneTime(tmp.getDoneTime());
            studentDto.setDoTime(tmp.getDoTime());
            studentDto.setScore(tmp.getScore());
            studentDto.setSTATUS(tmp.getStatus());
            studentDto.setSid(tmp.getSutdentId().toString());
            studentDtos.add(studentDto);
        }

         List<Student> sids = studentMapper.findBySid(student_homeWroks);
        for (int i = 0; i < sids.size(); i++) {
             StudentDto studentDto = studentDtos.get(i);
            studentDto.setRealName(sids.get(i).getRealName());
        }



        QueryResult<StudentDto> queryResult=new QueryResult<>();
        queryResult.setTotal(studentDtos.size());
        queryResult.setList(studentDtos);
        QueryResponseResult<StudentDto> queryResponseResult=new QueryResponseResult<>(CommonCode.SUCCESS,queryResult);
        return queryResponseResult;
    }

    public QueryResponseResult<HomeWrokDetailDto_T> showContent(Long sid,Long hid) {
         String detailHw = student_homeWrokMapper.findDetailHw(hid, sid);
        final List<HomeWrokDetailDto_T> homeWrokDetailDto_ts = JSON.parseArray(detailHw, HomeWrokDetailDto_T.class);
        QueryResult<HomeWrokDetailDto_T> queryResult=new QueryResult<>();
        queryResult.setList(homeWrokDetailDto_ts);
        queryResult.setTotal(homeWrokDetailDto_ts.size());
        QueryResponseResult<HomeWrokDetailDto_T> queryResponseResult=new QueryResponseResult<>(CommonCode.SUCCESS,queryResult);
        return queryResponseResult;
    }
}
